<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
    @close="cancel" class="custom-dialog">
    <div class="app-container">
      <div class="build-container">
        <el-steps :active="active" finish-status="success" align-center>
          <el-step title="全量汇集过程" description="汇集过程">1</el-step>
          <el-step title="配置信息" description="配置信息">2</el-step>
        </el-steps>

        <div v-show="active === 1" class="step1" style="height: 100%">
          <customToolbar ref="reader" @change="handleChange" :propsEdit="editObj" />
        </div>
        <div v-show="active === 2" class="step2">
          <Mapper ref="mapper" @done="handleDone" :propsEdit="editObj" />
        </div>
        <div v-show="active === 3" class="step3"></div>
        <div class="floating-div">
          <el-button :disabled="active === 1" v-if="active > 1" style="margin-top: 0px; float: right"
            @click="last">上一步</el-button>
          <el-button v-show="active !== 2" type="primary"
            style="position: absolute; margin-top: 0px; margin-bottom: 12px; float: right" @click="next">下一步</el-button>
          <el-button v-show="active == 2" type="primary" style="margin-top: 0px; margin-bottom: 12px; float: right"
            @click="createJob">提交</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<style scoped>
.floating-div {
  position: fixed;
  /* 使用固定定位，使元素固定在屏幕上 */
  bottom: 10%;
  /* 距离底部的距离，根据需要调整 */
  right: 10%;
  /* 距离右侧的距离，根据需要调整 */
  text-align: center;
  /* 文字居中对齐 */
  border-radius: 5px;
  /* 圆角边框，根据需要调整 */
  /*box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5); !* 阴影效果，根据需要调整 *!*/
}
</style>
<script>
import * as jobTemplate from '@/api/dataextractionrealtime/single.js'
import Pagination from '@/components/Pagination'
import JsonEditor from '@/components/JsonEditor'
import clip from '@/utils/clipboard'
import Reader from './reader'
import customToolbar from '../../../customToolbar/customToolbarForDataAllToCore.vue'
import Writer from './writer'
import Mapper from './mapper copy'
export default {
  props: {
    // 定义要接收的Props属性
    propValue: String, // 你可以在这里指定数据类型
    porpObj: Object,
  },
  name: 'single',
  components: { Reader, Writer, Pagination, Mapper, JsonEditor, customToolbar },
  data() {
    return {
      // openDailog: true,
      editObj: this.porpObj,
      dialogStatus: this.propValue,
      textMap: {
        update: '编辑接入任务',
        create: '新建全量接入任务',
      },
      dialogFormVisible: true,
      jobTemplateSelectDrawer: false,
      list: null,
      listLoading: true,
      readerInfo: {}, //reader返回信息
      writerInfo: {}, //writer返回信息
      jobConfig: {},
      togertherArr: [],
      extractionName: '', //数据集名称
      inputData: '',
      configJson: '', //JSON对象
      str: '', //json字符串
      active: 1,
      jsonData: {},
    }
  },
  created() { },
  methods: {
    cancel() {
      this.$emit('done')
    },
    async handleDone(info) {
      console.log('-info最终信息----' + JSON.stringify(info))
      this.jobConfig = info
    },
    async handleChange(type, info) {
      console.log('-type----' + type)
      if (type === 'reader') {
        this.readerInfo = info
        console.log('-reader-' + JSON.stringify(info))
      } else if (type === 'writer') {
        this.writerInfo = info
        console.log('-writer-' + JSON.stringify(info))
      } else if (type === 'jsonData') {
        let obj = {
          cells: {
            node: [],
          },
          edges: [],
        }
        info.cells.node.map((v, i) => {
          obj.cells.node.push({
            geometry: v.geometry,
            id: v.id,
            title: v.title,
            style: v.style,
          })
        })
        info.edges.map((v, i) => {
          obj.edges.push({
            edge: v.edge,
            geometry: v.geometry,
            id: v.id,
            source: {
              connectable: v.source.connectable,
              geometry: v.source.geometry,
              id: v.source.id,
              isGroup: v.source.isGroup,
              mxObjectId: v.source.mxObjectId,
              style: v.source.style,
              title: v.source.title,
              vertex: v.source.vertex,
            },
            target: {
              connectable: v.target.connectable,
              geometry: v.target.geometry,
              id: v.target.id,
              isGroup: v.target.isGroup,
              mxObjectId: v.target.mxObjectId,
              style: v.target.style,
              title: v.target.title,
              vertex: v.target.vertex,
            },
          })
        })

        this.jsonData = obj
      }
    },
    open() {
      this.dialogFormVisible = true
      this.active = 1
      this.rest()
    },
    next() {
      this.$refs.mapper.getName()

      console.log('jsonData====================' + JSON.stringify(this.jsonData.edges))
      console.log('writerInfo====================' + JSON.stringify(this.writerInfo))
      console.log('readerInfosss====================' + this.readerInfosss)
      console.log(this.jsonData, 'reader====================')
      console.log(this.writerInfo, 'writer')
      // const fromTableList = this.$refs.reader.getData().columns
      // const toTableList = this.$refs.writer.getData().columns
      // this.readerInfo = this.$refs.reader.getData()
      // this.writerInfo = this.$refs.writer.getData()
      // const fromTableName = this.$refs.reader.getData().tableName
      // 第一步 reader 判断是否已选字段
      if (this.jsonData.edges.length == this.jsonData.cells.node.length - 1) {
        if (this.jsonData.edges[0].source.title == '全量数据层抽取' && this.jsonData.edges[this.jsonData.edges.length - 1].target.title == '核心层加载') {
          let arr = []
          this.jsonData.edges.map((v, i) => {
            arr.push(v.source.title)
          })
          var countedNames = arr.reduce((obj, name) => {
            if (name in obj) {
              obj[name]++
            } else {
              obj[name] = 1
            }
            return obj
          }, {})
          if (countedNames.全量数据层抽取 == 2) {
            this.$message.error('只能连一条线')
          } else {
            if (this.active === 1) {
              // 实现第一步骤读取的表和字段直接带到第二步骤
              if (!this.readerInfo.tableId) {
                this.$message.error('没有完成全量数据区加载配置')
                return false
              }
              if (!this.writerInfo.incrementUpdateStyle) {
                this.$message.error('没有完成核心层加载抽取配置')
                return false
              } else {
                this.active++
                return false
              }
            } else {
              // 将第一步和第二步得到的字段名字发送到第三步
              if (this.active === 2) {
                // this.$refs.mapper.sendTables(fromTableList, toTableList)
              }
              if (this.active !== 4) {
                this.active++
              }
            }
            if (this.active === 4) {
              let arr = []
              this.readerColumns = []
              this.writerColumns = []
              // this.readerColumns=this.$refs.mapper.getLTables()
              this.$refs.mapper.getLTables().forEach((item) => {
                this.readerColumns.push(item.columnName)
              })
              this.$refs.mapper.getRTables().forEach((item) => {
                this.writerColumns.push(item.columnName)
              })
              // if(this.$refs.mapper.getLTables().length==this.$refs.mapper.getRTables().length){
              //   this.$refs.mapper.getLTables().forEach(item=>{
              //   this.$refs.mapper.getRTables().forEach(it=>{
              //      if(item.id==it.id){
              //        arr.push({
              //         sourceTableId:item.id,
              //         sourceTableName:item.tableName,
              //         targetTableId:it.id,
              //         targetTableName:it.tableName
              //        })
              //      }
              //   })
              // })
              // if(arr.length!=this.$refs.mapper.getLTables().length){
              //   this.$message.error('数据来源与目标数据源不一致')
              //   return
              // }
              // }else{
              //   this.$message.error('数据来源与目标数据源数量不一致')
              //   return
              // }
              this.detailList = arr
              this.extractionName = this.$refs.mapper.getName().extractionName
              this.status = this.$refs.mapper.getName().status
            }
          }
        } else {
          this.$message.error('连线顺序不正确，以全量数据层抽取为开始,以数据处理为中间，核心层加载为结束')
        }
      } else {
        this.$message.error('未连线')
      }
    },
    last() {
      if (this.active > 1) {
        this.active--
      }
    },
    chaneDate(datetime) {
      function addDateZero(num) {
        return num < 10 ? '0' + num : num
      }
      let d = new Date(datetime)
      let formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate())
      return formatdatetime
    },
    // 创建单任务
    createJob() {
      //配置信息
      const jbconfig = {
        filePath: this.jobConfig.filePath,
        scheduleType: this.jobConfig.scheduleType,
        scheduleLevel: this.jobConfig.scheduleLevel,
        advanceScheduling: this.jobConfig.advanceScheduling,
        driverMemory: this.jobConfig.driverMemory,
        cpuAudit: this.jobConfig.cpuAudit,
        executeUnitCount: this.jobConfig.executeUnitCount,
        executeUnitMemory: this.jobConfig.executeUnitMemory,
        scheduleTime: this.chaneDate(this.jobConfig.scheduleTime),
        rerunTime: this.jobConfig.rerunTime,
        cronExpression: this.jobConfig.cronExpression,
        effectTime: this.chaneDate(this.jobConfig.effectTime),
        failureTime: this.chaneDate(this.jobConfig.failureTime),
        dataCollectionScope: this.readerInfo.sourceDatasourceScopeType,
        dataUpdateMethod: this.writerInfo.incrementUpdateStyle,
      }
      console.log('==============jbconfig====' + JSON.stringify(jbconfig))
      console.log('==============readerInfo====' + JSON.stringify(this.readerInfo))
      var arr = []
      for (var i = 0; i < this.readerInfo.tableId.length; i++) {
        var readerDto = {
          dateColumn: this.readerInfo.tableId[i].extractionTimeField ? this.readerInfo.tableId[i].extractionTimeField : 'null',
          startTime: this.chaneDate(this.readerInfo.startTime),
          endTime: this.chaneDate(this.readerInfo.endTime),
        }
        // 映射数据
        var ColumnMappings = []
        for (var cl = 0; cl < this.readerInfo.tableId[i].columnList.length; cl++) {
          let status
          if (this.readerInfo.tableId[i].columnList[cl].status && this.readerInfo.tableId[i].columnList[cl].status === true) {
            status = 1
          } else {
            status = 0
          }
          var mappingObj = {
            sourceColumn: this.readerInfo.tableId[i].columnList[cl].columnName,
            targetColumn: this.readerInfo.tableId[i].columnList[cl].sourceColumn,
            columnType: this.readerInfo.tableId[i].columnList[cl].dataType,
            status: status,
          }
          ColumnMappings.push(mappingObj)
        }
        // var writerDto;
        // if(this.writerInfo.incrementUpdateStyle === '0'){
        //    writerDto ={
        //      primaryColumn:this.readerInfo.tableId[i].margeOnlyColumn,
        //   }
        // }
        // if(this.writerInfo.incrementUpdateStyle === '1'){
        //    writerDto ={
        //     dateColumn: this.readerInfo.tableId[i].margeDateColumn,
        //     startTime:this.chaneDate(this.readerInfo.tableId[i].writeStime),
        //     endTime:this.chaneDate(this.readerInfo.tableId[i].writeEtime),
        //      // whereParams:this.readerInfo.tableId[i].writerSql,
        //   }
        // }

        const dataExtractionDetailList = {
          targetTableName: this.readerInfo.tableId[i].sourceTable,
          targetTableId: this.readerInfo.tableId[i].sourceTableId,
          sourceTableName: this.readerInfo.tableId[i].table,
          sourceTableId: this.readerInfo.tableId[i].id,
          readerDto: readerDto,
          columnMappings: ColumnMappings,
          rdbmsWriterDto: {
            primaryColumn: this.writerInfo.selColumnList[0].margeOnlyColumn,
            updateType: this.writerInfo.selColumnList[0].replaceStyle,
            dateColumn: this.writerInfo.selColumnList[0].margeDateColumn,
            writerSql: this.writerInfo.selColumnList[0].writerSql,
            startTime: this.writerInfo.selColumnList[0].margeDateRange ? dayjs(this.writerInfo.selColumnList[0].margeDateRange[0]).format('YYYY-MM-DD HH:mm:ss') : null,
            endTime: this.writerInfo.selColumnList[0].margeDateRange ? dayjs(this.writerInfo.selColumnList[0].margeDateRange[1]).format('YYYY-MM-DD HH:mm:ss') : null,
          },
          addstr: JSON.parse(localStorage.getItem('addCharacterDto')) !== null ? JSON.parse(localStorage.getItem('addCharacterDto'))[i].list : undefined,
          addtime: JSON.parse(localStorage.getItem('addTimestampDto')) !== null ? JSON.parse(localStorage.getItem('addTimestampDto'))[i].list : undefined,
          addcol: JSON.parse(localStorage.getItem('addConstantDto')) !== null ? JSON.parse(localStorage.getItem('addConstantDto'))[i].list : undefined,
          tri: JSON.parse(localStorage.getItem('removeSpaceDto')) !== null ? JSON.parse(localStorage.getItem('removeSpaceDto'))[i].list : undefined,
          sub: JSON.parse(localStorage.getItem('subStringDto')) !== null ? JSON.parse(localStorage.getItem('subStringDto'))[i].list : undefined,
          del: JSON.parse(localStorage.getItem('eliminateCharacterDto')) !== null ? JSON.parse(localStorage.getItem('eliminateCharacterDto'))[i].list : undefined,
          nvl: JSON.parse(localStorage.getItem('nullConversionDto')) !== null ? JSON.parse(localStorage.getItem('nullConversionDto'))[i].list : undefined,
          rep: JSON.parse(localStorage.getItem('characterReplaceDto')) !== null ? JSON.parse(localStorage.getItem('characterReplaceDto'))[i].list : undefined,
        }
        arr.push(dataExtractionDetailList)
      }

      if (this.editObj.addroedit == 'update') {
        const obj = {
          id: this.porpObj.id,
          description: this.jobConfig.description,
          jobName: this.jobConfig.jobName,
          sourceDatasourceId: this.readerInfo.sourceId,
          sourceDatasourceName: this.readerInfo.sourceName,
          dataCollectionScope: this.readerInfo.isIncrement,
          jobConfig: jbconfig,
          sourceDatasourceScopeType: this.readerInfo.sourceDatasourceScopeType,
          jobGroup: '1692358527323836417',
          extractionStartTime: this.readerInfo.startTime,
          extractionEndTime: this.readerInfo.endTime,
          cronExpression: this.jobConfig.cronExpression,
          directoryId: this.jobConfig.directoryId,
          dataExtractionDetailList: arr,
          targetDatasourceId: this.writerInfo.sourceId,
          targetDatasourceName: this.writerInfo.sourceName,
          jsonData: this.jsonData,
          type: '2',
        }
        jobTemplate.addDataextractionJobupdate(obj).then((res) => {
          if (res.data.code == 0) {
            localStorage.removeItem('addCharacterDto')
            localStorage.removeItem('addTimestampDto')
            localStorage.removeItem('addConstantDto')
            localStorage.removeItem('removeSpaceDto')
            localStorage.removeItem('subStringDto')
            localStorage.removeItem('eliminateCharacterDto')
            localStorage.removeItem('nullConversionDto')
            localStorage.removeItem('characterReplaceDto')
            // 切回第一步
            this.$emit('refreshList')
            this.active = 1
            this.dialogFormVisible = false
            this.rest()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      } else {
        const obj = {
          description: this.jobConfig.description,
          jobName: this.jobConfig.jobName,
          sourceDatasourceId: this.readerInfo.sourceId,
          sourceDatasourceName: this.readerInfo.sourceName,
          dataCollectionScope: this.readerInfo.isIncrement,
          jobConfig: jbconfig,
          sourceDatasourceScopeType: this.readerInfo.sourceDatasourceScopeType,
          jobGroup: '1692358527323836417',
          extractionStartTime: this.readerInfo.startTime,
          extractionEndTime: this.readerInfo.endTime,
          cronExpression: this.jobConfig.cronExpression,
          directoryId: this.jobConfig.directoryId,
          dataExtractionDetailList: arr,
          targetDatasourceId: this.writerInfo.sourceId,
          targetDatasourceName: this.writerInfo.sourceName,
          jsonData: this.jsonData,
          type: '2',
        }
        jobTemplate.addDataextractionJob(obj).then((res) => {
          if (res.data.code == 0) {
            // 切回第一步
            localStorage.removeItem('addCharacterDto')
            localStorage.removeItem('addTimestampDto')
            localStorage.removeItem('addConstantDto')
            localStorage.removeItem('removeSpaceDto')
            localStorage.removeItem('subStringDto')
            localStorage.removeItem('eliminateCharacterDto')
            localStorage.removeItem('nullConversionDto')
            localStorage.removeItem('characterReplaceDto')
            this.$emit('refreshList')
            this.active = 1
            this.dialogFormVisible = false
            this.rest()
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          this.$message.error('请检查您的配置信息是否正确')
        })
      }

      // if(this.detailList.length==0){
      //   this.$message.error('请返回上一步检查所选数据')
      // }else{
      //       // 调api
      // jobTemplate.batchAddJob(obj).then(res => {
      //    
      //   // 切回第一步
      //   this.active = 1
      //   this.dialogFormVisible = false
      // })
      // }
    },
    rest() {
      setTimeout(() => {
        this.$refs.reader.rest()
        this.$refs.writer.rest()
        this.$refs.mapper.rest()
      }, 750)
    },
    //构建JSON
    bulid() {
      let obj = {
        rdbmsReader: {
          readerSplitPk: this.readerInfo.splitPk,
          whereParams: this.readerInfo.where,
          querySql: this.readerInfo.querySql,
        },
        rdbmsWriter: {
          preSql: this.writerInfo.preSql,
          postSql: this.writerInfo.postSql,
        },
        readerDatasourceId: this.readerInfo.sourceId,
        readerTables: [this.readerInfo.tableName],
        readerColumns: this.readerColumns,
        writerDatasourceId: this.writerInfo.targetDatasourceId,
        writerTables: [this.writerInfo.tableName],
        writerColumns: this.writerColumns,
      }
      jobTemplate.bulidJson(obj).then((res) => {
        if (res.data.code == 200) {
          this.str = res.data.data.replaceAll('&amp;', '&&')
          this.configJson = JSON.parse(res.data.data)
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    handleCopy(text, event) {
      clip(this.configJson, event)
      this.$message({
        message: 'copy success',
        type: 'success',
      })
    },
  },
  beforeDestroy() {
    localStorage.removeItem('addCharacterDto')
    localStorage.removeItem('addTimestampDto')
    localStorage.removeItem('addConstantDto')
    localStorage.removeItem('removeSpaceDto')
    localStorage.removeItem('subStringDto')
    localStorage.removeItem('eliminateCharacterDto')
    localStorage.removeItem('nullConversionDto')
    localStorage.removeItem('characterReplaceDto')
  },
}
</script>

<style lang="scss" scoped></style>
